<?php

namespace app\db\model;

use think\Db;
use think\Model;

class DbQuestion extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $dbName     = 'db_question';

    # --------------------------------- 查询类接口 START------------------------------------
    /**
     * 获取模板信息
     * @param int  $question_id 变量ID
     * @author MSQ 2021-8-2
    **/
    public function getDetails($question_id = 0,$field = '*')
    {
        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $info = $this->where(['id' => $question_id])->value($field);
        }else{
            $info = db($this->dbName)->field($field)->where(['id' => $question_id])->find();
        }
        
        return $info;
    }
    /**
     * 生成随机question_key
     * @param int  $question_key 指定key
     *             $item_key 上级key 变量组/模块key
     * @author MSQ 2021-8-2
    **/
    public function getQuestionKey($question_name = '',$item_key = '',$question_key = '')
    {
        // if (!$question_key) $question_key = $item_key.'_'.md5($question_name);
        # 用md5加密变量名 同一名称加密后是一样的会陷入死循环 用随机数好些
        if (!$question_key) $question_key = $item_key.'_'.uniqid();

        # 验证唯一性
        $isExist = $this->where(['question_key' => $question_key])->value('id');
        if ($isExist) $this->getQuestionKey($question_name,$item_key,'');
        return $question_key;
    }
    /**
     * 根据变量key获取信息
     * @param int  $question_key 指定key
     *             $item_key 上级key 变量组/模块key
     * @author MSQ 2021-8-2
    **/
    public function getQuestionListByQuestionKey($question_key = '',$field = '')
    {
        $where = [
            'status' => 1
        ];
        if (is_array($question_key)) {
            $where['question_key'] = ['IN',$question_key];

            if ($field && $field != '*' && count(explode(',', $field)) == 1) {
                // 只取一个字段
                $info = $this->where($where)->column('id,'.$field);
            }else{
                $info = db($this->dbName)->field($field)->where($where)->select();
            }
        }else{
            $where['question_key'] = $question_key;

            if ($field && $field != '*' && count(explode(',', $field)) == 1) {
                // 只取一个字段
                $info = $this->where($where)->value($field);
            }else{
                $info = db($this->dbName)->field($field)->where($where)->find();
            }
        }
        if (!$info) return [];
        return $info;
    }
    /**
     * 判断变量录入数据时是否需要value
     * @param int  $question_type 问题答案（填写）类型：1-单选题，2-多选题，3-下拉，4-附件上传，5-单行文本 6-多行文本 7-时间（Y-m-d）
     *             $question_id 变量id
     *             $value 回答的值
     * @author MSQ 2021-8-5
    **/
    public function checkQuestionIsNeedValue($question_type = 0,$question_id = 0,$value = '')
    {
        if (!$value) return 0;
        if (!$question_type && !$question_id) return 0;
        # 不知道类型 查询变量信息
        if (!$question_type) $question_type = $this->getDetails($question_id,'question_type');
        
        if (!$question_type) return 0;

        $needType = [1,2,3];
        # 允许录入value
        if (in_array($question_type,$needType)) return $value;

         return 0;
    }
    /**
     * 检测变量是否已存在
     * @author MSQ 2021-8-11
    **/
    public function checkQuestionExist($data = [])
    {
        # 是否已存在
        $whereCheckExist = [
            'q.item_id'       => $data['item_id'],
            'r.question_name' => $data['question_name'],
            'q.parent_id'     => isset($data['parent_id']) ? $data['parent_id'] : 0,
            'q.template_id'   => isset($data['template_id']) ? $data['template_id'] : 0,
            'q.status'        => 1,//未删除
            'r.status'        => 1,//未删除
        ];
        $question_id = $this->alias('q')
            ->join('db_template_relation_question r','r.question_id = q.id')
            ->where($whereCheckExist)
            ->value('q.id');
        if (!$question_id) return 0;
        return $question_id;
    }
    /**
     * 获取基本信息变量信息
     * @author MSQ 2021-8-17
    **/
    public function getBasicInfo($field = '*')
    {
        $basicItemId = model('DbItem')->getBasicItemInfo('id');
        $where = ['item_id' => $basicItemId,'create_type' => 0];
        $info  = model('DbQuestion')->customQuery($where,$field);

        return $info;
    }
    /**
     * 获取导出病例固定变量key
     * QID 性别 出生日期
     * @author MSQ 2021-8-24
    **/
    public function getExportFixedQuestionKey()
    {
        $basicItemKey = model('DbItem')->getBasicItemKey();
        $key = [
            $basicItemKey.'__user_number',// QID
            $basicItemKey.'__user_sex',// 性别
            $basicItemKey.'__user_birthday',// 出生日期
        ];
        return $key;
    }
    /**
     * 获取导出病例固定变量
     * QID 性别 出生日期
     * @author MSQ 2021-8-24
    **/
    public function getExportFixedQuestion($field = '*')
    {
        $exportFixedQuestionKey = $this->getExportFixedQuestionKey();
        $info = $this->getQuestionListByQuestionKey($exportFixedQuestionKey,$field);
        return $info;
    }
    /**
     * 自定义SQL
     * @author MSQ 2021-9-8
     */
    public function customQuery($where = [],$field = '')
    {
        $where['status'] = 1;

        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $info = $this->where($where)->column($field);
        }else{
            $info = db($this->dbName)->field($field)->where($where)->select();
        }

        return $info;
    }
    # ---------------------------------- 查询类接口 END-------------------------------------
    # ------------------------------- 验证数据类接口 START ---------------------------------
    /**
     * 验证编辑变量数据合法性
     * 避免设置模板时变量为单选/多选/下拉框但没有选项引起报错
     * @author MSQ 2021-9-10
     */
    public function checkEditQuestionLegitimacy($database_id = 0,$template_id = 0,$questionInfo = 0,$data = [])
    {
        # 新增变量 无需验证修改
        if (!$data['question_id'] || !$data['relation_id']) return ['code' => 1,'msg' => '非修改'];
        # 创建数据库设置模板
        if (!$template_id) return ['code' => 1,'msg' => '非修改'];

        if (!$questionInfo || !$data) return ['code' => 0,'msg' => '参数错误'];

        # questionInfo为变量id 获取变量信息
        if (!is_array($questionInfo)) $questionInfo = model('DbTemplateRelationQuestion')->getDetails($questionInfo,$template_id);

        if (!$questionInfo) return ['code' => 0,'msg' => '变量不存在或已删除'];

        # 是否有修改
        $isEdit = $this->checkQuestionIsEdit($template_id,$questionInfo,$data);
        if (!$isEdit) return ['code' => 1,'msg' => '未修改'];

        # 系统变量不允许修改
        if (!$questionInfo['create_type']) return ['code' => 0,'msg' => '系统变量不允许修改'];
        
        # 已有回答不允许修改或更改模块
        $isData = model('DbData')->getDataByQuestionId($database_id,$data['question_id'],'id',true);
        if ($isData) {
            if ($questionInfo['item_id'] != $data['item_id']) return ['code' => 0,'msg' => '存在回答不允许更改所属模块'];
            return ['code' => 0,'msg' => '存在回答不允许编辑'];
        }

        return ['code' => 1,'msg' => '验证通过'];
    }
    /**
     * 验证变量是否有改动
     * 避免设置模板时变量为单选/多选/下拉框但没有选项引起报错
     * @author MSQ 2021-9-10
     */
    public function checkQuestionIsEdit($template_id = 0,$questionInfo = [],$data = [])
    {
        if (!$template_id || !$questionInfo || !$data) return false;
        # 变量类型有修改
        if ($questionInfo['question_type'] != $data['question_type']) return true;
        # 变量名称有修改
        if ($questionInfo['question_name'] != $data['question_name']) return true;
        # 所属模块有修改
        if ($questionInfo['item_id'] != $data['item_id']) return true;
        # 所属变量组有修改
        if ($questionInfo['parent_id'] != $data['parent_id']) return true;

        # 单选/多选/下拉框 类型不变 检索选项是否相同
        # 此处仅检索选项是否有修改 选项数据合法性不在此处验证
        if (in_array($questionInfo['question_type'],[1,2,3])) {

            # 获取原变量选项列表
            $oldOptionList = model('DbTemplateRelationQuestionOption')->getOptionListByQId($template_id,$data['question_id'],'',false);
            $oldOptionList = array_column($oldOptionList,NULL,'option_id');

            $newOptionList = array_column($data['option_list'],NULL,'option_id');
            # 数量是否相同
            if (count($oldOptionList) != count($newOptionList)) return true;

            foreach ($oldOptionList as $oldKey => $oldValue) {
                # 修改之后的选项信息
                $newValue = @$newOptionList[$oldKey];
                if (!$newValue) return true;
                # 选项名称及is_other是否有修改
                
                if ($newValue['option_name'] != $oldValue['option_name']) return true;

                if ($newValue['is_other'] != $oldValue['is_other']) return true;
            }
        }
        return false;
    }
    # ---------------------------------- 查询类接口 END-------------------------------------

    # ------------------------------- 数据处理类接口 START ---------------------------------
    /**
     * 创建变量
     * @param int  $question_type 问题答案（填写）类型：1-单选题，2-多选题，3-下拉，4-附件上传，5-单行文本 6-多行文本 7-时间（Y-m-d）
     *             $question_id 变量id
     *             $value 回答的值
     * @author MSQ 2021-8-11
    **/
    public function createQuestion($data = [])
    {
        if (!isset($data['item_id']) || !$data['item_id'] || !isset($data['question_name']) || !$data['question_name'] || !isset($data['question_type']) || !in_array($data['question_type'], [0,1,2,3,4,5,6,7]) ) return false;
        if (in_array($data['question_type'],[1,2,3]) && (!isset($data['option_list']) || !$data['option_list'])) return false;//单选//多选//下拉
        # 二级变量 不允许question_type为0
        if (@$data['parent_id'] && !$data['question_type']) return false;

        $addData = [];
        $template_id = isset($data['template_id']) ? $data['template_id'] : 0;
        $database_id = isset($data['database_id']) ? $data['database_id'] : 0;
        $usercare_id = isset($data['usercare_id']) ? $data['usercare_id'] : 0;

        $addData['item_id']       = $data['item_id'];
        $addData['question_name'] = $data['question_name'];
        # 变量类型 1-单选题 2-多选题 3-下拉 4-附件上传 5-单行文本 6-多行文本 7-时间（Y-m-d）
        $addData['question_type'] = $data['question_type'];
        # 模板id 0为系统创建
        $addData['template_id']   = $template_id;
        $addData['database_id']   = $database_id;
        $addData['usercare_id']   = $usercare_id;

        # 父级question_id
        if (isset($data['parent_id'])) $addData['parent_id'] = $data['parent_id'];
        if (isset($data['question_key']) && $data['question_key']) {
            # 引用question 在原有key后面加上随机数
            # 不过这会违背原本key的生成规则 原本是以所属模块的key作为前缀后面跟着加密的变量名，后续可以通过question_key找到所属模块
            # 而现在这种规则前面跟着的应该是引用变量对应模块的信息，并不是它自己的模块，不过变量后续的所属模块是可以改的，以模块作为前缀好像就没有意义了(除非编辑时生成新的key)此种规则的好处是可以知道变量的来源，因为引用了同一个变量它们的前缀是一样的，简而言之这样生成的item_key和question_key和option_key都只能找到引用的key即系统推荐的那一套模块的信息并不能找到当前模板的信息
            $addData['question_key'] = $data['question_key'].'&'.uniqid();
        }else{
            # 新增question 重新生成key
            $item_key = model('DbItem')->getDetails($data['item_id'],'item_key');
            $addData['question_key'] = $this->getQuestionKey($data['question_name'],$item_key);
        }
        # 问题值单位
        if (isset($data['question_unit'])) $addData['question_unit'] = $data['question_unit'];
        # 文本输入提示语
        if (isset($data['input_placeholder'])) $addData['input_placeholder'] = $data['input_placeholder'];
        # 变量描述
        if (isset($data['question_describe'])) $addData['question_describe'] = $data['question_describe'];
        # 排序权重
        if (isset($data['weight'])) $addData['weight'] = $data['weight'];
        # 创建状态 0-系统固定 1-医务自定义添加 2-导入
        if (isset($data['create_type'])) $addData['create_type'] = $data['create_type'];
        
        /*$question_id = $this->checkQuestionExist($data);
        if (!$question_id) {*/
            $this->setAttr('id',null)->isUpdate(false)->save($addData);
            if (!isset($this->id)) return false;
            $question_id = $this->id;
        // }
        if (in_array($data['question_type'],[1,2,3])) {
            # 创建选项
            $addOptionRes = model('DbQuestionOption')->createOption($question_id,$data['option_list'],$template_id,$usercare_id);
            if (!$addOptionRes) return false;
        }
        return $question_id;
    }
    /**
     * 根据删除目录/模块
     * @param [type] $question_id 变量id
     * @author MSQ   2021-8-21
     */
    public function deleteQuestionByIds($question_id = [])
    {
        if (!$question_id) return false;

        if (!is_array($question_id)) $question_id = [$question_id];

        $where = [
            'status' => 1,
            'id'     => ['IN',$question_id]
        ];
        $res = $this->update(['status' => 0],$where);
        if (!$res) return false;
        return true;
    }
    /**
     * 添加数据
     * @author MSQ 2021-9-1
     */
    public function addData($data = [])
    {
        if (!$data) return false;
        
        $this->setAttr('id',null)->isUpdate(false)->save($data);
        if (!isset($this->id)) return false;

        return $this->id;
    }
    # -------------------------------- 数据处理类接口 END ----------------------------------


}
